package com.zgf.easy.proxy.handler;

import com.zgf.easy.proxy.mgr.ObjectMgr;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @project: easy_proxy
 * @author: zgf1
 * @date: 2021/12/26 13:25
 */
public class InvocationHandlerImpl implements InvocationHandler {

    private final Class<Future> FutrueCls = Future.class;
    private final ThreadPoolExecutor executor;
    private Class<?> clazz;
    private String identity;

    public InvocationHandlerImpl(ThreadPoolExecutor executor) {
        this.executor = executor;
    }

    public void setClazz(Class<?> clazz) {
        this.clazz = clazz;
    }

    public void setIdentity(String identity) {
        this.identity = identity;
    }

    @Override
    public Object invoke(Object proxy, final Method method, final Object[] args) throws Throwable {
        final Object obj = ObjectMgr.get(identity, clazz);
        if (obj == null) {
            throw new IllegalAccessError(identity+"身份下，接口" + clazz.getName() + "没有实现");
        }
        if (executor == null || !FutrueCls.isAssignableFrom(method.getReturnType())) {
            return method.invoke(obj, args);
        }
        return executor.submit(new Callable() {
            @Override
            public Object call() throws Exception {
                Object result = method.invoke(obj, args);
                return ((Future)result).get();
            }
        });
    }

}
